import axios from 'axios'
import ReactDOM from 'react-dom'
import { Loading, Toast } from 'antd-mobile'
import { createBrowserHistory } from 'history'
import { getToken } from './token.js'

const history = createBrowserHistory();

// 默认配置
const request = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/conner' : 'https://api.it120.cc/conner'
})

// 当前正在请求的数量
let requestCount = 0

// 显示loading
function showLoading() {
  if (requestCount === 0) {
    var dom = document.createElement('div')
    dom.setAttribute('id', 'loading')
    document.body.appendChild(dom)
    ReactDOM.render(<Loading color='red'/>, dom)
  }
  requestCount++
}

// 隐藏loading
function hideLoading() {
  requestCount--
  if (requestCount === 0) {
    document.body.removeChild(document.getElementById('loading'))
  }
}

// 添加拦截器
request.interceptors.request.use(
  function (config) {
     // 请求头+token
     if (getToken()) {
      config.headers['X-Token'] = getToken()
      if (config.method === 'post') {
        // config.data =  qs.parse(config.data)
        // config.data['X-Token'] = getToken()
        // config.data =  qs.stringify(config.data)
        // console.log(config.data);
        // config.data.append('token', getToken())
      }
      if (config.method === 'get') {
        config.params.token = getToken()
      }
    }
    if (config.headers.isLoading !== false) {
      showLoading()
    }


   



    return config
  },
  function (error) {
    if (error.config.headers.isLoading !== false) {
      hideLoading()
    }
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  function (response) {
    // 判断当前请求是否设置了不显示Loading
    if (response.config.headers.isLoading !== false) {
      hideLoading()
    }
    const errCode = [401, 403, 2000];
    if (errCode.includes(response.data.code)) {
      // 弹出错误提醒 清除缓存 跳转到登录页
      Toast.show({
        icon: 'fail',
        content: '登录失效',
        duration: 1000,
        afterClose: () => {
          localStorage.removeItem('token')
          history.push('/login')
          history.go(0)
        }
      })
    }
    return response
  },
  function (error) {
    if (error.config.headers.isLoading !== false) {
      hideLoading()
    }
    return Promise.reject(error)
  }
)

export default request
